<template>
  <div class="search-result">
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad"
    >
      <van-cell
        v-for="(article, index) in list"
        :key="index"
        :title="article.title"
      />
    </van-list>
  </div>
</template>

<script>
import { getSearchResults } from '@/api/search'
export default {
  name: 'SearchResult',
  components: {},
  props: {
    searchText: {
      type: String,
      required: true,
    },
  },
  data() {
    return {
      list: [],
      loading: false,
      finished: false,
      page: 1,
      perPage: 10,
    }
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {},
  methods: {
    async onLoad() {
      // 1.请求获取数据
      try {
        const { data: res } = await getSearchResults({
          // 页码
          page: this.page,
          // 每页的大小
          per_page: this.perPage,
          // 查询关键词
          q: this.searchText,
        })
        // 2.将数据添加到数组列表中
        const { results } = res.data
        this.list.push(...results)
        // 3.将本次的loading关闭
        this.loading = false
        // 4.判断是否有数据
        if (results.length) {
          this.page++
        } else {
          // 如果没有，则将加载状态 finished 设置为结束
          this.finished = true
        }
      } catch (err) {
        // 展示加载失败的
        this.error = false
        // 加载失败了 loading 也要关闭
        this.loading = true
      }
    },
  },
}
</script>

<style lang="less">
</style>
